package com.tian.service.impl;

import com.tian.message.SendEmailMessage;
import com.tian.service.SendEmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * {@code @description:} 发送html邮件
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-08-13 22:43
 * {@code @version:} 1.0
 */
@Slf4j
@Service("sendEmailHTMLMessageService")
public class SendEmail4HtmlServiceImpl implements SendEmailService {
    private final JavaMailSender javaMailSender;

    //邮件发送方邮箱
    @Value("${spring.mail.username}")
    private String MailSender;

    public SendEmail4HtmlServiceImpl(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    @Override
    public Boolean sendEmail(SendEmailMessage sendEmailMessage) {
        //1、获取MimeMessage对象，多用途的网际邮件扩充协议
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper;

        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            //2、设置邮件发送者
            mimeMessageHelper.setFrom(MailSender);
            //3、设置邮件接受方
            mimeMessageHelper.setTo(sendEmailMessage.getRecipientEmail());
            //4、设置邮件主题
            mimeMessageHelper.setSubject(sendEmailMessage.getRecipientEmail());
            //5、设置邮件内容（HTML格式邮件内容），带html格式第二个参数true
            mimeMessageHelper.setText(sendEmailMessage.getContent(), true);
            //6、发送邮件
            javaMailSender.send(mimeMessage);
            log.info("html格式的邮件发送成功");
            return true;
        } catch (MessagingException e) {
            log.error("sendHtmlMail 邮件发送失败：{}", e.getMessage());
            return false;
        }
    }
}
